package com.nondo.dean.product.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nondo.dean.common.tool.AliyunOssTool;
import com.nondo.dean.common.tool.BeanUtils;
import com.nondo.dean.common.tool.RestTemplateUtils;
import com.nondo.dean.common.tool.StringUtils;
import com.nondo.dean.common.web.View;
import com.nondo.dean.product.domain.Brand;
import com.nondo.dean.product.domain.Product;
import com.nondo.dean.product.domain.ProductCategory;
import com.nondo.dean.product.domain.ProductExample;
import com.nondo.dean.product.domain.ProductLog;
import com.nondo.dean.product.domain.ProductRelative;
import com.nondo.dean.product.domain.ProductType;
import com.nondo.dean.product.domain.ProductWithBLOBs;
import com.nondo.dean.product.domain.Series;
import com.nondo.dean.product.mapper.BrandMapper;
import com.nondo.dean.product.mapper.ProductExtendsMapper;
import com.nondo.dean.product.mapper.ProductMapper;
import com.nondo.dean.product.mapper.SeriesMapper;
import com.nondo.dean.product.model.AppProductBean;
import com.nondo.dean.product.model.AttachBean;
import com.nondo.dean.product.model.AuthUserBean;
import com.nondo.dean.product.model.BrandBean;
import com.nondo.dean.product.model.CategoryBean;
import com.nondo.dean.product.model.GradeBean;
import com.nondo.dean.product.model.ProductBean;
import com.nondo.dean.product.model.ProductBomBean;
import com.nondo.dean.product.model.SeriesBean;
import com.nondo.dean.product.model.UserBean;
import com.nondo.dean.product.model.param.ProductOrderParam;
import com.nondo.dean.product.model.param.ProductParam;
import com.nondo.dean.product.model.param.ProductQueryParam;
import com.nondo.dean.product.model.result.OrderProductResult;
import com.nondo.dean.product.model.result.ProductResult;

/**
 * @author ken.
 * @version 1.0
 * @email 695093513@qq.com
 * @date 2018/3/27
 */
@Component
public class ProductService {
    public static final int SHELF_STATUS_DOWN = 0;//下架
    public static final int SHELF_STATUS_UP = 1;//上架
    public static final String IS = "是";
    public static final String NO = "否";
    public static final String PLANK = "门板";
    public static final String MARBLE = "大理石茶几";
    public static final String SET_OF = "套";

    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private ProductExtendsMapper productExtendsMapper;
    
    @Autowired
    UserService userService;

    @Autowired
    ProductTypeService productTypeService;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SeriesMapper seriesMapper;

    @Autowired
    private ProductLogService productLogService;

    @Autowired
    private ProductRelativeService productRelativeService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ProductExtendsMapper productInterface;

    @Autowired
    ProductAttachService productAttachService;

    @Autowired
    AliyunOssTool aliyunOssTool;

    @Autowired
    ProductCategoryService productCategoryService;
    
    @Autowired
    ProductBomService productBomService;
    
    @Autowired
    private ProductMixService productMixService;

    public long getProductCount() {
        ProductExample productExample = new ProductExample();
        return productMapper.countByExample(productExample);
    }

    /**
     * 根据主键ID查询产品
     *
     * @param id
     * @return
     */
    public ProductWithBLOBs selectById(int id) {
        return this.productMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据主键ID查询处理后的产品
     *
     * @param id
     * @return
     */
    @SuppressWarnings("rawtypes")
    public ProductBean findById(int id) {
        ProductWithBLOBs productWithBLOBs = this.selectById(id);
        ProductBean productBean = new ProductBean();
        BeanUtils.copy(productWithBLOBs, productBean);

        //品牌
        if (productBean.getBrandId() > 0) {
            BrandBean brandBean = this.getBrand(productBean.getBrandId());
            productBean.setBrand(brandBean);
        } else {
            productBean.setBrand(new BrandBean());
        }

        //系列
        if (productBean.getSeriesId() > 0) {
            SeriesBean series = this.getSeries(productBean.getSeriesId());
            productBean.setSeries(series);
        } else {
            productBean.setSeries(new SeriesBean());
        }

        //等级
        if (productBean.getGradeId() > 0) {
            GradeBean gradeBean = this.getGrade(productBean.getGradeId());
            productBean.setGrade(gradeBean);
        } else {
            productBean.setGrade(new GradeBean());
        }

        //主图处理
        if (StringUtils.isNoneEmpty(productBean.getMainImage())) {
            productBean.setMainImage(this.aliyunOssTool.getFileUrl(productBean.getMainImage()));
        }

        //产品属性处理
        if (StringUtils.isNotEmpty(productBean.getProperties())) {
            JSONArray jsonArray = JSON.parseArray(productBean.getProperties());
            productBean.setPropertiesList(jsonArray);
        } else {
            productBean.setPropertiesList(new ArrayList());
        }
        
        //产品规格处理
        if (StringUtils.isNotEmpty(productBean.getSpecifications())) {
            JSONArray jsonArray = JSON.parseArray(productBean.getSpecifications());
            productBean.setSpecificationsList(jsonArray);
        } else {
            productBean.setSpecificationsList(new ArrayList());
        }


        //图片列表
        List<AttachBean> attachBeanList = this.getAttach(productBean.getId());
        productBean.setAttach(attachBeanList);

        //日志
        List<ProductLog> productLogList = this.productLogService.selectByProductId(productBean.getId());
        productBean.setLogs(productLogList);

        //分类
        if (productBean.getCategoryId() > 0) {
            CategoryBean categoryBean = this.getCategory(productBean.getCategoryId());
            productBean.setCategory(categoryBean);
            productBean.setpCategoryId(categoryBean.getPid());
            CategoryBean pCategoryBean = this.getCategory(categoryBean.getPid());
            productBean.setpCategory(pCategoryBean);
        } else {
            productBean.setCategory(new CategoryBean());
            productBean.setpCategory(new CategoryBean());
            productBean.setpCategoryId(0);
        }
        
        //父分类
        if (productBean.getCategoryId() > 0) {
            CategoryBean categoryBean = this.getCategory(productBean.getCategoryId());
            productBean.setCategory(categoryBean);
            productBean.setpCategoryId(categoryBean.getPid());
        } else {
            productBean.setCategory(new CategoryBean());
            productBean.setpCategoryId(0);
        }

        return productBean;
    }


    /**
     * 根据主键进行更新
     *
     * @param productWithBLOBs
     * @return
     */
    public int update(ProductWithBLOBs productWithBLOBs) {
        return this.productMapper.updateByPrimaryKeyWithBLOBs(productWithBLOBs);
    }

    /**
     * 获取列表
     *
     * @param offset
     * @param limit
     * @param productWithBLOBs
     * @return
     */
    public List<ProductWithBLOBs> getList(int offset, int limit, ProductParam productWithBLOBs) {
        ProductExample example = new ProductExample();
        example.setOrderByClause("id asc");
        RowBounds rowBounds = new RowBounds(offset, limit);
        ProductExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, productWithBLOBs);
        List<ProductWithBLOBs> productList = productMapper.selectByExampleWithBLOBsWithRowbounds(example, rowBounds);

        //处理关联信息
        ArrayList newList = new ArrayList();
        for (ProductWithBLOBs item : productList) {
            ProductBean productBean = new ProductBean();
            BeanUtils.copy(item, productBean);

            //品牌
            if (item.getBrandId() > 0) {
                BrandBean brandBean = this.getBrand(item.getBrandId());
                productBean.setBrand(brandBean);
            } else {
                productBean.setBrand(new BrandBean());
            }

            //系列
            if (item.getSeriesId() > 0) {
                SeriesBean series = this.getSeries(item.getSeriesId());
                productBean.setSeries(series);
            } else {
                productBean.setSeries(new SeriesBean());
            }

            //等级
            if (item.getGradeId() > 0) {
                GradeBean gradeBean = this.getGrade(item.getGradeId());
                productBean.setGrade(gradeBean);
            } else {
                productBean.setGrade(new GradeBean());
            }

            //主图处理
            if (StringUtils.isNoneEmpty(item.getMainImage())) {
                productBean.setMainImage(this.aliyunOssTool.getFileUrl(item.getMainImage()));
            }

            //图片列表
            List<AttachBean> attachBeanList = this.getAttach(productBean.getId());
            productBean.setAttach(attachBeanList);

            //产品属性处理
            if (StringUtils.isNotEmpty(productBean.getProperties())) {
                productBean.setPropertiesList(JSON.parseArray(productBean.getProperties()));
            } else {
                productBean.setPropertiesList(new ArrayList());
            }

            //产品分类
            if (productBean.getCategoryId() > 0) {
                CategoryBean categoryBean = this.getCategory(productBean.getCategoryId());
                productBean.setCategory(categoryBean);
            }

            newList.add(productBean);
        }

        return newList;
    }

    /**
     * 数据统计
     *
     * @param productWithBLOBs
     * @return
     */
    public Long count(ProductParam productWithBLOBs) {
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, productWithBLOBs);
        return productMapper.countByExample(example);
    }

    /**
     * 数据统计 系列 分类
     *
     * @param productWithBLOBs
     * @return
     */
    public Long countProduct(ProductWithBLOBs productWithBLOBs) {
        ProductExample example = new ProductExample();
        if(productWithBLOBs.getCategoryId() != null && productWithBLOBs.getSeriesId()==0){
            example.createCriteria().andShelfStatusEqualTo(1).andCategoryIdEqualTo(productWithBLOBs.getCategoryId()).andDelFlagEqualTo(ProductCategory.DEL_FLAG_NORMAL);
        }else if(productWithBLOBs.getSeriesId() != null && productWithBLOBs.getCategoryId()==0){
            example.createCriteria().andSeriesIdEqualTo(productWithBLOBs.getSeriesId()).andDelFlagEqualTo(ProductCategory.DEL_FLAG_NORMAL).andShelfStatusEqualTo(1);
        }else{
            example.createCriteria().andCategoryIdEqualTo(productWithBLOBs.getCategoryId()).andSeriesIdEqualTo(productWithBLOBs.getSeriesId()).andDelFlagEqualTo(ProductCategory.DEL_FLAG_NORMAL).andShelfStatusEqualTo(1);
        }
        return productMapper.countByExample(example);
    }

    /**
     * 系列下 分类的产品总数统计
     * @param productWithBLOBs
     * @return
     */
    public Long countSeriesProduct(ProductWithBLOBs productWithBLOBs) {
        String ids="";
        List<ProductCategory> categorieList = productCategoryService.selectProductCategoryById(productWithBLOBs.getCategoryId());
        for(ProductCategory beans : categorieList){
            ids+=beans.getId()+",";
        }
        ids=ids.substring(0,ids.length() - 1);
        return productExtendsMapper.countSeriesCategory(ids,productWithBLOBs.getSeriesId());
    }


    /**
     * 产品基本信息列表
     * @param offset
     * @param limit
     * @param product
     * @return List<{@link Product}>
     */
    public List<Product> getProductList(Integer offset, Integer limit, ProductParam productWithBLOBs) {
        ProductExample example = new ProductExample();
        example.setOrderByClause("id asc");
        RowBounds rowBounds = new RowBounds(offset, limit);
        ProductExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, productWithBLOBs);
        List<Product> productList = productMapper.selectByExampleWithRowbounds(example, rowBounds);
        return productList;
    }

    /**
     * 设置查询条件
     *
     * @param criteria
     * @param productWithBLOBs
     */
    void setCriteria(ProductExample.Criteria criteria, ProductParam productWithBLOBs) {
        if (productWithBLOBs != null) {
            //查询ID
            if (productWithBLOBs.getId() != null) {
                criteria.andIdEqualTo(productWithBLOBs.getId());
            }

            //名字模糊查询
            if (StringUtils.isNoneBlank(productWithBLOBs.getName())) {
                criteria.andNameLike("%" + productWithBLOBs.getName() + "%");
            }

            //编号模糊查询
            if (StringUtils.isNoneBlank(productWithBLOBs.getCode())) {
                criteria.andCodeLike("%" + productWithBLOBs.getCode() + "%");
            }

            //品牌查询
            if (productWithBLOBs.getBrandId() != null) {
                criteria.andBrandIdEqualTo(productWithBLOBs.getBrandId());
            }
            
            //类型
            if (productWithBLOBs.getTypeId() != null) {
                criteria.andTypeIdEqualTo(productWithBLOBs.getTypeId());
            }

            //等级
            if (productWithBLOBs.getGradeId() != null) {
                criteria.andGradeIdEqualTo(productWithBLOBs.getGradeId());
            }

            //系列
            if (productWithBLOBs.getSeriesId() != null) {
                criteria.andSeriesIdEqualTo(productWithBLOBs.getSeriesId());
            }
            
            if (CollectionUtils.isNotEmpty(productWithBLOBs.getSeriesIds())) {
                criteria.andSeriesIdIn(productWithBLOBs.getSeriesIds());
            }
            
            //分类
            if (productWithBLOBs.getCategoryId() != null) {
                criteria.andCategoryIdEqualTo(productWithBLOBs.getCategoryId());
            }
            
            if (CollectionUtils.isNotEmpty(productWithBLOBs.getCategoryIds())) {
                criteria.andCategoryIdIn(productWithBLOBs.getCategoryIds());
            }

            //是否可以下单
            if (StringUtils.isNoneEmpty(productWithBLOBs.getOrderFlag())) {
                criteria.andOrderFlagEqualTo(productWithBLOBs.getOrderFlag());
            }

            //事业部代码
            if (StringUtils.isNoneEmpty(productWithBLOBs.getBusinessCode())) {
                criteria.andBusinessCodeEqualTo(productWithBLOBs.getBusinessCode());
            }

            //淘汰状态
            if (productWithBLOBs.getStatus() != null) {
                criteria.andStatusEqualTo(productWithBLOBs.getStatus());
            }

            //上下架状态
            if (productWithBLOBs.getShelfStatus() != null) {
                criteria.andShelfStatusEqualTo(productWithBLOBs.getShelfStatus());
            }
        }
        criteria.andDelFlagEqualTo(Product.DEL_FLAG_NORMAL);
    }

    /**
     * 根据品牌ID获取品牌信息
     *
     * @param brandId
     * @return
     */
    public BrandBean getBrand(int brandId) {
        if (brandId <= 0) {
            return new BrandBean();
        }
        Brand brand = this.brandMapper.selectByPrimaryKey(brandId);
        BrandBean brandBean = new BrandBean();
        BeanUtils.copy(brand, brandBean);
        return brandBean;
    }

    /**
     * 根据产品ID获取系列
     *
     * @param seriesId
     * @return
     */
    public SeriesBean getSeries(int seriesId) {
        if (seriesId <= 0) {
            return new SeriesBean();
        }
        Series series = this.seriesMapper.selectByPrimaryKey(seriesId);
        SeriesBean seriesBean = new SeriesBean();
        BeanUtils.copy(series, seriesBean);
        return seriesBean;
    }

    /**
     * 获取分类信息
     *
     * @param categoryId
     * @return
     */
    public CategoryBean getCategory(int categoryId) {
        CategoryBean categoryBean = new CategoryBean();
        if (categoryId <= 0) {
            return categoryBean;
        }
        ProductCategory productCategory = this.productCategoryService.selectProductCategory(categoryId);
        BeanUtils.copy(productCategory, categoryBean);

        return categoryBean;
    }

    /**
     * 按照名称查询商品
     *
     * @param name 商品名称
     * @return 产品列表 List<{@link Product}>
     */
    public List<Product> getProductListByName(String name) {
        List<Product> productList = new ArrayList<Product>();
        if (StringUtils.isBlank(name)) {
            return productList;
        }
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        criteria.andNameLike("%" + name.trim() + "%");
        criteria.andDelFlagEqualTo(Product.DEL_FLAG_NORMAL);
        productList = this.productMapper.selectByExample(example);
        return productList;
    }

    /**
     * 根据productId查询关联产品
     *
     * @param id 产品主ID
     * @return 产品列表 List<{@link Product}>
     */
    public List<Product> getRelativeProductListById(Integer id) {
        List<Product> productList = new ArrayList<Product>();
        List<ProductRelative> productRelativeList = null;
        productRelativeList = this.productRelativeService.getRelativeProductListByProductId(id);
        for (ProductRelative productRelative : productRelativeList) {
            Integer relativeProductId = productRelative.getRelativeProductId();
            Product product = this.productMapper.selectByPrimaryKey(relativeProductId);
            productList.add(product);
        }
        return productList;
    }

    /**
     * 获取等级信息
     *
     * @param greadId
     * @return
     */
    public GradeBean getGrade(int gradeId) {
        GradeBean gradeBean = new GradeBean();
//        RestTemplateUtils.reInitMessageConverter(restTemplate);
        View resultJson = restTemplate.postForEntity("http://dean-platform/platform/v1/inner/grade/info/" + gradeId, null, View.class).getBody();
        if (resultJson.getCode() == 20000 && resultJson.getData() != null) {
            BeanUtils.copy(resultJson.getData(), gradeBean);
        }

        return gradeBean;
    }

    /**
     * 获取附件列表
     *
     * @param productId
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<AttachBean> getAttach(int productId) {
        //1、获取产品附件关联列表
        List list = this.productAttachService.getAttachIdList(productId);

        List<AttachBean> newList = new ArrayList<AttachBean>();
        //2、获取产品附件列表
        if (list.size() > 0) {
            RestTemplateUtils.reInitMessageConverter(restTemplate);
            String params = JSON.toJSONString(list);
            View resultJson = restTemplate.postForEntity("http://dean-platform/platform/v1/inner/attach/list", params, View.class).getBody();

            if (resultJson.getCode() == 20000 && resultJson.getData() != null) {
                //将结果转换为列表
                String stringJson = JSON.toJSONString(resultJson.getData());
                List<Map> listJson = JSON.parseArray(stringJson, Map.class);
                //循环处理data数据
                for (Map<String, Object> item : listJson) {
                    AttachBean attachBean = AttachBean.valueFrom(item);
                    attachBean.setUrl(aliyunOssTool.getImgUrl(attachBean.getName()));
                    newList.add(attachBean);
                }
            }
        }

        return newList;
    }

    /**
     * 检查产品物料数据是否存在
     *
     * @return
     */
    public List<Product> checkMaterialDuplicate(Product product) {
        //检查数据是否存在
        ProductExample productCheck = new ProductExample();
        productCheck.createCriteria().andCodeEqualTo(product.getCode());

        List<Product> productExist = this.productMapper.selectByExample(productCheck);

        return productExist;
    }

    /**
     * 插入产品物料到库
     *
     * @param productList
     * @return
     */
    public int SynMaterial(List<Product> productList) {
        int count = 0;
        try {
            //获取所有产品类型
            HashMap<String, ProductType> prodMap = productTypeService.selectProductTypeAll();
            for (Product product : productList) {
                product.setStock(100000);
                //是否可下单
                String orderFlag = product.getOrderFlag();
                ProductType productType = prodMap.get(product.getTypeCode());
                if (productType == null) {
                    continue;
                }

                //产品类型主键Id
                Integer productType_id = productType.getId();
                product.setTypeId(productType_id);

                if (IS.equals(orderFlag)) {
                    if (product.getCode().startsWith("BQ")) {
                        orderFlag = NO;
                    }
                } else if (NO.equals(orderFlag)) {
                    //所有门板可以下单
                    if (product.getCode().indexOf(PLANK) > -1 || product.getCode().endsWith("-1A") || product.getCode().endsWith("-2A") || product.getCode().endsWith("-3A")) {
                        orderFlag = IS;
                    } else if (",E5102P-1A,AA001C".indexOf("," + product.getCode() + ",") > -1) {
                        orderFlag = IS;
                    } else if (product.getName().indexOf(MARBLE) > -1 && product.getCode().startsWith("G")) {
                        orderFlag = IS;
                    } else if (product.getCode().startsWith("GX") || product.getCode().startsWith("GS") && SET_OF.equals(product.getUnit())) {
                        orderFlag = IS;
                    }
                }
                //检查数据是否存在
                List<Product> productExist = checkMaterialDuplicate(product);

                if (productExist.size() > 0) {
                    for (Product item : productExist) {
                        //执行修改
                        product.setId(item.getId());
                        ProductWithBLOBs productWithBLOBs = new ProductWithBLOBs();
                        BeanUtils.copy(product, productWithBLOBs);
                        count += productMapper.updateByPrimaryKeySelective(productWithBLOBs);
                    }
                } else {
                    //新增
                    ProductWithBLOBs productWithBLOBs = new ProductWithBLOBs();
                    BeanUtils.copy(product, productWithBLOBs);
                    count += productMapper.insertSelective(productWithBLOBs);

                }

            }
        } catch (Exception e) {
            return 0;
        }
        return count;
    }

    /**
     * 库存数据入库
     *
     * @param list
     * @return
     */
    public int synProductInventory(List<Product> list) {
        productInterface.updateInventoryAll();
        int i = 0;
        for (Product product : list) {
            //参考库存
            if ("EX_KC".equals(product.getInventoryType())) {

                ProductExample productExample = new ProductExample();
                productExample.createCriteria().andCodeEqualTo(product.getCode());
                i += productMapper.updateByExample(product, productExample);
                //在制库存
            } else if ("EX_MD".equals(product.getInventoryType())) {

                ProductExample productExample = new ProductExample();
                productExample.createCriteria().andCodeEqualTo(product.getCode());
                i += productMapper.updateByExample(product, productExample);
            }
        }
        productInterface.updateDeleteStauts();


        return i;
    }

    /**
     * 按照主键ID查询产品基本信息
     *
     * @param id 产品ID
     * @return {@link ProductResult}
     */
    public ProductResult getProductResultById(Integer id) {
        Product product = productMapper.selectByPrimaryKey(id);
        return ProductResult.covertToBean(product);
    }
    
    /**
     * 减库存（防超卖）加销量
     * @param productId 产品ID
     * @param purchaseNum 采购产品数量
     * @return 影响行数
     */
    public int updateStockSaleNum(ProductOrderParam orderParam) {
        return productExtendsMapper.updateStockSaleNum(orderParam);
    }

    /**
     * 查询单个商品信息
     *
     * @param request
     * @param response
     * @param code 产品编码
     * @return 商品详细信息 {@link Product}
     */
    public Product selectByCode(String code) {
        List<Product> productList = new ArrayList<Product>();
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(code);
        criteria.andDelFlagEqualTo(Product.DEL_FLAG_NORMAL);
        productList = this.productMapper.selectByExample(example);
        return CollectionUtils.isNotEmpty(productList) ? productList.get(0) : null;
    }

    /**
     * 按照名称查询可下单商品
     *
     * @param name 商品名称
     * @return 产品列表 List<{@link Product}>
     */
    public List<OrderProductResult> getOrderProductListByName(String name) {
        List<OrderProductResult> productResultList = new ArrayList<OrderProductResult>();
        if (StringUtils.isBlank(name)) {
            return productResultList;
        }
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        criteria.andOrderFlagEqualTo("是");
        criteria.andNameLike("%" + name.trim() + "%");
        criteria.andDelFlagEqualTo(Product.DEL_FLAG_NORMAL);
        List<Product> productList = this.productMapper.selectByExample(example);
        for (Product product : productList) {
            OrderProductResult productResult = new OrderProductResult();
            BeanUtils.copy(product, productResult);
            List<ProductBomBean> productBomList = productBomService.selectByParentProductCode(product.getCode());
            List<OrderProductResult.OrderProduct> childProductList = new ArrayList<OrderProductResult.OrderProduct>();
            for (ProductBomBean productBom : productBomList) {
                OrderProductResult.OrderProduct orderProduct = new OrderProductResult.OrderProduct();
                BeanUtils.copy(selectByCode(productBom.getProductCode()), orderProduct);
                childProductList.add(orderProduct);
            }
            productResult.setChildList(childProductList);
            productResultList.add(productResult);
        }
        return productResultList;
    }

    /**
     * 批量修改产品属性
     * @return 影响行数
     */
    public int batchUpdateProductProperties() {
        int num = 0;
        ProductExample example = new ProductExample();
        List<ProductWithBLOBs> productList = productMapper.selectByExampleWithBLOBs(example);
        for (ProductWithBLOBs productWithBLOBs : productList) {
            String properties = productWithBLOBs.getProperties();
            if (StringUtils.isEmpty(properties)) {
                continue;
            }
            JSONArray jsonArray = JSON.parseArray(properties);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                jsonObject.put("name", jsonObject.getString("key").trim());
                jsonObject.put("value", jsonObject.getString("value").trim());
                jsonObject.put("key", i + 1);
            }
            properties = JSON.toJSONString(jsonArray);
            productWithBLOBs.setProperties(properties);
            num += productMapper.updateByPrimaryKeySelective(productWithBLOBs);
        }
        return num;
    }

    /**
     * 
     * 获取APP产品详情数据
     * @param productWithBLOBs 
     * @return {@link AppProductBean}
     */
    @SuppressWarnings("rawtypes")
    public AppProductBean getAppProductInfo(ProductBean productBean) {
        AppProductBean appProductBean = new AppProductBean();
        
        BeanUtils.copy(productBean, appProductBean);

        //主图处理
        if (StringUtils.isNoneEmpty(appProductBean.getMainImage())) {
            appProductBean.setMainImage(this.aliyunOssTool.getFileUrl(appProductBean.getMainImage()));
        }
        //图片列表
        List<AttachBean> attachBeanList = this.getAttach(appProductBean.getId());
        appProductBean.setAttach(attachBeanList);
        //产品属性处理
        if (StringUtils.isNotEmpty(appProductBean.getProperties())) {
            appProductBean.setPropertiesList(JSON.parseArray(appProductBean.getProperties()));
        } else {
            appProductBean.setPropertiesList(new ArrayList());
        }
        //产品规格处理
        if (StringUtils.isNotEmpty(productBean.getSpecifications())) {
            productBean.setSpecificationsList(JSON.parseArray(productBean.getSpecifications()));
        } else {
            productBean.setSpecificationsList(new ArrayList());
        }
        //参与的产品组合
        appProductBean.setProductMixList(this.productMixService.getProductMixListByProductId(appProductBean.getId()));
        // 经销商的接单员手机号
        UserBean userBean = userService.getUserBeanByName(userService.getLoginUserName());
        if (userBean == null)
            return appProductBean;
        AuthUserBean authUserBean = userService.getAuthUserByUserName(userBean.getOrderTakeUser());
        if (authUserBean == null)
            return appProductBean;
        appProductBean.setContactNumber(authUserBean.getMobile());
        
        return appProductBean;
    }

    /**
     * 查看某个产品的子件产品
     * @param productParam
     * @return
     */
    public List<ProductResult> getChildListByCode(ProductQueryParam productParam) {
        List<ProductResult> productList = productExtendsMapper.getChildListByCode(productParam);
        return productList;
    }

}
